package com.example.demo.service;

import com.example.demo.dmain.dto.User;
import com.example.demo.dmain.entity.UserEntity;
import com.example.demo.dmain.req.UserQueryReq;
import com.example.demo.mapper.UserMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
@Transactional(propagation = Propagation.REQUIRES_NEW)

public class UserService {

    @Resource
    private UserMapper userMapper;

    public User LoginIn(String username, String password) {
        System.out.println("username"+username+"password"+password);
        return userMapper.getInfo(username,password);
    }

    public User getInfoByName(String username) {
        return userMapper.selectByName(username);
    }
    public User getInfoById(Long userId) {
        return userMapper.selectById(userId);
    }
    public int addUser(UserEntity userEntity){
        System.out.println("user"+userEntity);
        User info = userMapper.selectByName(userEntity.getUserName());
        if(info==null){
            User user = new User();
            user.setUserName(userEntity.getUserName());
            user.setRealName(userEntity.getRealName());
            user.setPassword(userEntity.getPassword());
            user.setPhone(userEntity.getPhone());
            user.setRoles(String.join("，", userEntity.getUserRoles()));
            return userMapper.insert(user);
        }else return -1;
    }

    public int update(UserEntity userEntity){
        System.out.println("user"+userEntity);
        User user = userMapper.selectByName(userEntity.getUserName());
        user.setUserId(userEntity.getUserId());
        user.setRoles(String.join("，", userEntity.getUserRoles()));
        return userMapper.updateById(user);
    }

    public List<UserEntity> queryUserList(UserQueryReq userQueryReq) {
        List<UserEntity> userEntities = new ArrayList<>();
        List<User> users = userMapper.queryUserList(userQueryReq);
        for (User user : users) {
            UserEntity userEntity = new UserEntity();
            userEntity.setUserId((user.getUserId()));
            userEntity.setUserName(user.getUserName());
            userEntity.setRealName(user.getRealName());
            userEntity.setPassword(user.getPassword());
            userEntity.setPhone(user.getPhone());
            if(!user.getRoles().equals(null)){
                userEntity.setUserRoles(Arrays.asList(user.getRoles().split("，")));
            }
            userEntities.add(userEntity);
        }
        return userEntities;
    }

    public void deleteUser(Long id) {
        userMapper.deleteById(id);
    }
}
